package com.evaluation_system.controller;

import ch.qos.logback.classic.Logger;
import com.evaluation_system.Util.JwtUtil;
import com.evaluation_system.pojo.DTO.LoginInfoDTO;
import com.evaluation_system.pojo.DTO.ResetPasswordDTO;
import com.evaluation_system.pojo.JwtProperties;
import com.evaluation_system.pojo.Result.Result;
import com.evaluation_system.pojo.VO.LoginInfoVO;
import com.evaluation_system.pojo.entity.LoginInfo;
import com.evaluation_system.pojo.entity.VerifyCode;
import com.evaluation_system.service.IVerifyCodeGen;
import com.evaluation_system.service.LoginService;
import com.evaluation_system.service.ResetPasswordService;
import com.evaluation_system.service.impl.SimpleCharVerifyCodeGenImpl;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class LoginController {
    /**
     * 登录接口，将请求的用户名和密码封装到 User 对象中
     */
    private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(UserController.class);
    @Autowired
    private LoginService loginService;
    @Autowired
    private ResetPasswordService resetPasswordService;
    @Autowired
    private JwtProperties jwtProperties;
    @PostMapping("/login")
    public Result<LoginInfoVO> login(@RequestBody LoginInfoDTO loginUser, HttpServletRequest request) {
        log.info("用户登录：{}", loginUser);
        if (loginUser == null) {
            return Result.error("用户名或密码错误，或角色未选择正确");
        }
        // 校验验证码
        String inputCode = loginUser.getCaptcha(); // 前端传来的验证码
        String sessionCode = (String) request.getSession().getAttribute("VerifyCode"); // session 中的验证码

        if (sessionCode == null || inputCode == null || !sessionCode.equalsIgnoreCase(inputCode)) {
            return Result.error("验证码错误");
        }

        LoginInfo userloginfo = null;
        String role=loginUser.getRole();

        switch (role) {
            case "uploader":
                userloginfo = loginService.uploaderlogin(loginUser);
                break;
            case "checker":
                userloginfo = loginService.checkerlogin(loginUser);
                break;
            case "evaluator":
                userloginfo = loginService.evaluatorlogin(loginUser);
                break;
            case "admin":
                userloginfo = loginService.adminlogin(loginUser);
                break;
            default:
                return Result.error("非法角色类型");
        }
        // 登录失败时，返回错误信息
        if (userloginfo == null) {
            return Result.error("用户名或密码错误");
        }

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userloginfo.getId());
        claims.put("role", role);
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        LoginInfoVO logInfoVO = LoginInfoVO.builder()
                .id(userloginfo.getId())
                .username(userloginfo.getUsername())
                .role(role)
                .token(token)
                .build();
        return Result.success(logInfoVO);
    }

    @PostMapping("/resetpassword")
    public Result<String> register(@RequestBody ResetPasswordDTO resetPasswordDTO) {
        log.info("重置密码：{}", resetPasswordDTO);
        boolean success = false;

        switch (resetPasswordDTO.getRole().toLowerCase()) {
            case "uploader":
                success = resetPasswordService.uploaderresetpassword(resetPasswordDTO);
                break;
            case "checker":
                success = resetPasswordService.checkerresetpassword(resetPasswordDTO);
                break;
            case "evaluator":
                success = resetPasswordService.evaluatorresetpassword(resetPasswordDTO);
                break;
            default:
                return Result.error("非法的角色类型");
        }
        if (success) {
            return Result.success("密码重置成功");
        } else {
            return Result.error("密码重置失败，请检查用户名或其他信息");
        }
    }

    @ApiOperation(value = "验证码")
    @GetMapping("/verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
        IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
        try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            String code = verifyCode.getCode();
            LOGGER.info(code);
            //将VerifyCode绑定session
            request.getSession().setAttribute("VerifyCode", code);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
            LOGGER.info("", e);
        }
    }

}
